package com.airlines.base.config.jsr303;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import com.airlines.base.config.response.ResponseResult;
import com.airlines.base.config.response.ResponseResultBuilder;
import com.airlines.common.BeanFiledUtils;

/**
 * @author xxxx
 * @date 2018年6月8日 
 * @description JSR303验证工具类
 */
public class ValidateUtil {
    /** 
     * 判断是否有验证错误信息 ，并将所有错误信息汇总，并且response错误码置为400
     * @param result 
     * @return 
     */  
    public static String validateWithResponse(BindingResult result, HttpServletResponse response) {  
        if(result.hasErrors()){  
            response.setStatus(HttpStatus.BAD_REQUEST.value());  
            return getFileErrorMessage(result);  
        }  
        return "success";  
    }
    
    
    /** 
     * 判断是否有验证错误信息 ，并将所有错误信息汇总
     * @param result 
     * @return 
     */  
    public static String validate(BindingResult result) {  
        if(result.hasErrors()){  
            return getFileErrorMessage(result);
        }  
        return "success";  
    }
    
    /**
     * 推荐的验证方式
     * @param result
     * @param response
     * @return
     */
    public static ResponseResult<String> validateDefault(BindingResult result, HttpServletResponse response) {  
        if(result.hasErrors()){  
        	String errorMessage = getErrorMessage(result);
            response.setStatus(HttpStatus.BAD_REQUEST.value());  
            return ResponseResultBuilder.errorResult(null, errorMessage,String.valueOf(HttpStatus.BAD_REQUEST.value()));
        }  
        return ResponseResultBuilder.successResult("", "success");  
    }
        
    public static String getFileErrorMessage(BindingResult result){
    	List<FieldError> list = result.getFieldErrors();
    	StringBuilder sb = new StringBuilder();  
        for(FieldError  fileError:list){  
        	sb.append("\n"+fileError.getField()+":"+fileError.getDefaultMessage()); 
        } 
        return sb.toString();
    }
    
    public	 static String getErrorMessage(BindingResult result){
   	 List<ObjectError> list = result.getAllErrors();  
        StringBuilder sb = new StringBuilder();  
        for(ObjectError  error:list){  
        	String field = "";
        	try {
        		field = (String) BeanFiledUtils.forceGetFieldValue(error, "field");
        		sb.append("\n"+field+":"+error.getDefaultMessage()); 
				} catch (Exception e) {
					e.printStackTrace();
					sb.append("\n"+error.toString());
				}
        	
        } 
        return sb.toString();
   }
    
}
